
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

let home = () => Promise.resolve(import('../views/home/home.vue'))   //了解
let cates = () => import('../views/cates/cates.vue')
let login = () => import('../views/login/login.vue')
let register = () => import('../views/register/register.vue')
let my = () => import('../views/my/my.vue')
let index = () => import('../views/index/index.vue')
let list = () => import('../views/list/list.vue')
let detail = () => import('../views/detail/detail.vue')
let pay = () => import('../views/pay/pay.vue')
let search=()=> import('../views/search/search.vue')
let order=()=> import('../views/oreder/order.vue')
let address=()=> import('../views/address/address.vue')
let address_add=()=> import('../views/address/address-add.vue')
let router = new VueRouter({
  mode: 'hash',//默认是hash  history(无#号)
  routes: [
    {
      path: '/login',
      components: {
        default: login,
      },
      meta: {
        title: '登录'
      }
    },
    {
      path:'/search',
      component:search,
      name:'search'
    },
    {
      path: '/index',  //要承载 home/my/shop/cates4个页面的 ，要在index.vue中要占坑：<router-view>
      component: index,  //这4个页面要展示的公共的东西就要放在index.vue中
      children: [
        {
          path: 'my',
          component: my,
          meta: {
            title: '我的'
          }
        },
        {
          path: 'shop',
          component: () => import('../views/shop/shop.vue'),
          meta: {
            title: '购物车'
          }
        },   //   /index/shop
        {
          path: 'cates',
          component: cates,
          meta: {
            title: '分类'
          }
        },
        {
          path: 'home',
          component: home,
          meta: {
            title: '首页'
          }
        },
        {
          path: '',
          redirect: 'home'
        }
      ]
    },
    {
      path: '/list',
      component: list,
      name: 'list11',//为路由起个名称

    },
    {
      path: '/detail/:id/:type',
      component: detail,
      name: 'detail'
    },
    {
      path: '/pay',
      component: pay,
      name: 'pay'
    },
    {
      path: '/register',
      component: register,
      name: 'register'
    },
    {
      path:'/order',
      component:order
    },
    {
      path:'/address',
      component:address,
    },
    {
      path:'/add_address',
      component:address_add,
    },
    {
      path: "*",
      redirect: '/index'
    }
  ],
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) { //如果你滚动了，则第3个参数有具体的位置
      return savedPosition
    } else {
      return { x: 0, y: 0 }
    }
  }
})

export default router
// 1. 全局前置守卫 ，进来之前进行一个拦截判断
router.beforeEach((to, from, next) => { //和后端的中间件非常类似
  if (to.path == '/login') { //如果访问的是login，直接放行 无需验证
    next()
    return
  }
  if (!localStorage.getItem('userInfo')) { 
    next('/login') 
    return
  }
  next() 
})
